﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using TrafficArchives.Common;
using TrafficArchives.DataAccess;
using TrafficArchives.Utilities;

namespace TrafficArchives
{
    public partial class Login : Page
    {
        private readonly HtmlInputHidden _btnScreen = new HtmlInputHidden();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Initlize();
            }
        }

        private void Initlize()
        {
            var userCodeCookie = Request.Cookies["UserCode"];
            if (userCodeCookie != null && !string.IsNullOrEmpty(userCodeCookie.Value))
            {
                TxtUser.Text = userCodeCookie.Value;
            }
            _btnScreen.ID = "_btnScreen";
            _btnScreen.Name = "_btnScreen";
            FindControl("form1").Controls.Add(_btnScreen);
            ScriptManager.RegisterOnSubmitStatement(this, GetType(), "Screen", "document.all.form1._btnScreen.value=window.screen.height;\r\n");
        }

        protected void BtnLoginClick(object sender, EventArgs e)
        {
            if (Sign())
            {
                var screen = Request.Form["_btnScreen"];
                Response.Cookies.Add(new HttpCookie("ScreenHeight", screen));
                Response.Redirect("Default.aspx");
            }
            else
            {
                TxtPasswordValidator.Visible = false;
                LblMsg.Visible = true;
                LblMsg.Text = "密码错误。";
                UpdatePanelMain.Update();
            }
        }

        private bool Sign()
        {
            var user = TxtUser.Text.Trim('\'');
            var pwd = Md5.Encrypt(TxtPassword.Text);
            var conn1 = new Condition
                            {
                                FieldName = "usercode", 
                                Operator = ConditionOperator.Equal, 
                                Values = new object[] {user}
                            };
            var conn2 = new Condition
                            {
                                FieldName = "userpassword", 
                                Operator = ConditionOperator.Equal,
                                Values = new object[] { pwd }
                            };
            var request = new Request();
            request.Items.Add(conn1);
            request.Items.Add(conn2);
            try
            {
                var db = new UserDb();
                var users = db.GetData(request);
                if (users.Data.Rows.Count > 0)
                {
                    LoginUser.Current.IsLogined = true;
                    LoginUser.Current.IsSupperAdmin = users.Data.Rows[0]["isinternal"].ToString() == "1";
                    LoginUser.Current.UserId = users.Data.Rows[0]["user_id"].ToString();
                    LoginUser.Current.UserCode = users.Data.Rows[0]["UserCode"].ToString();
                    LoginUser.Current.UserName = users.Data.Rows[0]["username"].ToString();
                    LoginUser.Current.RoleId = users.Data.Rows[0]["userrole_id"].ToString();
                    LoginUser.Current.RoleName = LoginUser.Current.IsSupperAdmin
                                                     ? "超级管理员"
                                                     : users.Data.Rows[0]["rolename"].ToString();
                    LoginUser.Current.DepartmentId = users.Data.Rows[0]["GLBM_ID"].ToString();
                    LoginUser.Current.DepartmentName = users.Data.Rows[0]["GLBMNAME"].ToString();

                    LoginUser.Current.MenuString = users.Data.Rows[0]["powerassemble"].ToString();
                    Response.Cookies.Add(new HttpCookie("UserCode", LoginUser.Current.UserCode));
                }
                else
                {
                    LoginUser.Current.IsLogined = false;
                }
                return LoginUser.Current.IsLogined;
            }catch(Exception)
            {
                return false;
            }
        }
    }
}